import React, { useDebugValue, useEffect, useState, KeyboardEvent } from "react";
import { RatingProps } from "./Rating";
import styles from "./Rating.module.css";
import cn from 'classnames';
import StarIcon from './star.svg';

export const Rating = ({ isEditable=false, rating, setRating, className, ...props }: RatingProps): JSX.Element => {
    const [rattingArray, setRattingArray] = useState<JSX.Element[]>(new Array(5).fill(<></>))
    useEffect(()=>{
        constructRating(rating)
    },[rating])

    const constructRating = (currentRating:number) => {
        const updatedAr = rattingArray.map((r:JSX.Element, i:number) => {
            return (
            <span
                className={cn(styles.star, {
                    [styles.filled]: i < currentRating,
                    [styles.editable]: isEditable
                })}
                onMouseEnter = {()=>changeDisplay(i+1)}
                onMouseLeave = {()=>changeDisplay(rating)}
                onClick = {()=>onClick(i+1)}
                onKeyDown = {(e:KeyboardEvent<SVGElement>) => isEditable && handleSpace(i+1, e)}
            >
                <StarIcon
                    tabIndex = {isEditable ? 0 : -1}
                />
            </span>)
        })
        setRattingArray(updatedAr);
    }
    const changeDisplay = (i:number) => {
        if (!isEditable) {
            return;
        }
        constructRating(i)
    }
    const handleSpace = (rating: number, event: KeyboardEvent<SVGElement>) => {
        if (event.code != 'Space' || !setRating) {
            return;
        }
        setRating(rating)
    }

    const onClick = (i:number) => {
        if (!isEditable || !setRating) {
            return;
        }
        setRating(i)
    }

    return (<div {...props}>
        {rattingArray.map((r,i)=> (<span key={i}>{r}</span>))}
    </div>);
}